package org.apache.flink.kubernetes.resourceprovider;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptionsInternal;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.runtime.entrypoint.FlinkParseException;
import org.apache.flink.runtime.resourceprovider.ResourceProviderRunner;
import org.apache.flink.runtime.util.EnvironmentInformation;
import org.apache.flink.runtime.util.JvmShutdownSafeguard;
import org.apache.flink.runtime.util.SignalHandler;
import org.apache.flink.util.Preconditions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.flink.util.Preconditions.checkNotNull;

/** This class is the executable entry point for running a TaskExecutor in a Kubernetes pod. */
public class KubernetesResourceProviderRunner {

    protected static final Logger LOG = LoggerFactory.getLogger(KubernetesResourceProviderRunner.class);

    public static void main(String[] args) {
        EnvironmentInformation.logEnvironmentInfo(LOG, "Kubernetes ResourceProvider runner", args);
        SignalHandler.register(LOG);
        JvmShutdownSafeguard.installAsShutdownHook(LOG);

        runTaskManagerSecurely(args);
    }

    private static void runTaskManagerSecurely(String[] args) {
        Configuration configuration = null;

        try {
            configuration = ResourceProviderRunner.loadConfiguration(args);
            final String nodeId = System.getenv().get(Constants.ENV_FLINK_POD_NODE_ID);
            Preconditions.checkState(
                    nodeId != null,
                    "The environment variable %s is not set, "
                            + "which is used to identify the node where the task manager is located.",
                    Constants.ENV_FLINK_POD_NODE_ID);
            configuration.setString(TaskManagerOptionsInternal.PROVIDER_MANAGER_NODE_ID, nodeId);
        } catch (FlinkParseException fpe) {
            LOG.error("Could not load the configuration.", fpe);
            System.exit(ResourceProviderRunner.FAILURE_EXIT_CODE);
        }

        ResourceProviderRunner.runProviderManagerProcessSecurely(checkNotNull(configuration));
    }
}
